package com.spark.data.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.TextView
import com.spark.data.R
import com.spark.data.model.FolderModel

class FolderView(context: Context, attrs: AttributeSet?, defStyle: Int) : LinearLayout(context, attrs, defStyle) {
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context) : this(context, null, 0)

    init {
        orientation = VERTICAL
    }

    fun bind(datas: MutableList<FolderModel.FileModel>) {
        datas.forEach {
            val child = FileInfoView(context)
            child.bind(it)
            addView(child)
        }
        invalidate()
    }
}

class FileInfoView(context: Context, attrs: AttributeSet?, defStyle: Int) : LinearLayout(context, attrs, defStyle) {
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context) : this(context, null, 0)

    private val cb: CheckBox = rootView.findViewById(R.id.cb)
    private val tvName: TextView = rootView.findViewById(R.id.tv_name)

    private var folderItemModel: FolderModel.FileModel? = null

    init {
        cb.setOnCheckedChangeListener { _, isChecked ->
            folderItemModel?.isSelected = isChecked
        }
        rootView.setOnClickListener {
            val beforeState = cb.isChecked
            folderItemModel?.isSelected = !beforeState
        }
    }

    override fun getRootView(): View {
        return LayoutInflater.from(context).inflate(R.layout.item_file_two, this)
    }

    fun bind(data: FolderModel.FileModel) {
        cb.isChecked = data.isSelected
        tvName.text = data.name
    }
}